<template>
  <view class="view-class">
    <u-navbar :is-back="false" title="宿舍保洁"></u-navbar>
    <view class="view-box">
      <u-form :model="form" ref="uForm" label-width="180" label-align="center">
        <u-form-item required label="宿舍地址" prop="dormitoryAddress"><u-input v-model="form.dormitoryAddress" type="textarea" :auto-height="true"  disabled  /></u-form-item>
        <u-form-item required label="楼栋号" prop="building"><u-input v-model="form.building"  disabled /></u-form-item>
        <u-form-item required label="房间号" prop="roomId"><u-input v-model="form.roomId"  disabled /></u-form-item>
        <u-form-item required label="保洁员姓名" prop="cleaningName"><u-input v-model="form.cleaningName"  disabled /></u-form-item>
        <u-form-item required label="保洁员电话" prop="cleaningPhone"><u-input v-model="form.cleaningPhone" disabled type="number" /></u-form-item>
        <u-form-item required label="宿舍客厅照片" prop="bedImages">
          <u-upload  width="160" height="160" max-count="6" :header="uploadHeader"  :action="clUplodUrl" @on-remove="uploadRemove" @on-success="uploadSuccess"
                    ref="handIdCardUpload" ></u-upload>
        </u-form-item>
        <u-form-item required label="宿舍房间照片" prop="bedImages">
          <u-upload  width="160" height="160" max-count="6" :header="uploadHeader" :action="clUplodUrl" @on-remove="uploadRemove2" @on-success="uploadSuccess2"
                    ref="handIdCardUpload2" ></u-upload>
        </u-form-item>
        <u-form-item required label="宿舍卫生间照片" prop="bedImages">
          <u-upload  width="160" height="160" max-count="6" :header="uploadHeader" :action="clUplodUrl" @on-remove="uploadRemove3" @on-success="uploadSuccess3"
                    ref="handIdCardUpload3" ></u-upload>
        </u-form-item>
        <u-form-item required label="宿舍厨房照片" prop="bedImages">
          <u-upload  width="160" height="160" max-count="6" :header="uploadHeader" :action="clUplodUrl" @on-remove="uploadRemove4" @on-success="uploadSuccess4"
                    ref="handIdCardUpload4" ></u-upload>
        </u-form-item>
        <u-form-item required label="宿舍阳台照片" prop="bedImages">
          <u-upload  width="160" height="160" max-count="6" :header="uploadHeader" :action="clUplodUrl" @on-remove="uploadRemove5" @on-success="uploadSuccess5"
                    ref="handIdCardUpload5" ></u-upload>
        </u-form-item>
      </u-form>
      <u-button style="position: fixed;bottom: 0;left: 0;width: 100%;z-index: 9" type="primary" @click="submitFunc" v-if="!isSuccess">提交</u-button>
      <u-button style="position: fixed;bottom: 0;left: 0;width: 100%;z-index: 9" type="primary" @click="submitFunc('success')" v-else>完成</u-button>
    </view>
    <u-select v-model="showContactRelationSel" :list="contactRelationList" mode="single-column"
              @confirm="selectedContactRelation"></u-select>
    <u-top-tips ref="uTips"></u-top-tips>
    <u-modal v-model="show" confirm-text="退出"
             title="提示"  @confirm="submitFunc('success')"
    >
      <view class="u-update-content">
        <rich-text style="text-align: center;padding: 30rpx" :nodes="content"></rich-text>
      </view>
    </u-modal>
  </view>
</template>
<script>
import {compressImg} from '@/utils/compressor/compress.js'
import {uploadImg} from '@/utils/upload.js'
import {isEmpty} from "@/utils";
import * as consts from "@/utils/constant.js";
import clUpload from '../../../uni_modules/cl-upload/components/cl-upload/cl-upload.vue'
// import uniRate from '@/uni_modules/uni-rate/'
export default {
  components:{
    clUpload
  },
  data() {
    return {
      show:false,
      content:'未查询到宿舍信息，暂时无法操作！',
      rules:{
        cleaningName: [{required: true,message: '请输入保洁员姓名',trigger: ['change','blur'],}],
        dormitoryAddress: [{required: true,message: '请输入地址',trigger: ['change','blur'],}],
        building: [{required: true,message: '请输入宿舍楼栋',trigger: ['change','blur'],}],
        roomId: [{required: true,message: '请输入房间号',trigger: ['change','blur'],}],
        cleaningPhone: [{
          required: true,
          message: '请输入手机号',
          trigger: ['change','blur'],
        },
          {
            // 自定义验证函数，见上说明
            validator: (rule, value, callback) => {
              // 上面有说，返回true表示校验通过，返回false表示不通过
              // this.$u.test.mobile()就是返回true或者false的
              return this.$u.test.mobile(value);
            },
            message: '手机号码不正确',
            // 触发器可以同时用blur和change
            trigger: ['change','blur'],
          }],
      },
      form: {},
      sexList: [
        {
          name: '男',
          checked: false,
          disabled: false
        },
        {
          name: '女',
          checked: false,
          disabled: false
        }
      ],
      checkboxList: [
        {
          name: '是',
          checked: false,
          disabled: false
        },
        {
          name: '否',
          checked: false,
          disabled: false
        },
      ],
      radio: '',
      switchVal: false,
      showImages:false,
      showIdCardBadgeImages:false,
      showIdCardPortraitImgPreview:false,
      idCardPopup:true,
      idCardForm:{},
      isCRM:false,
      calendarShow:false,
      mode: 'date',
      //同行人员相关
      // 关系列表
      contactRelationList: [],
      showContactRelationSel:false,
      tzryPopup:false,
      tzryForm:{},
      isSuccess:false,
      videoList:[],
      fileList:[],
      fileList2:[],
      fileList3:[],
      fileList4:[],
      fileList5:[],
      clUplodUrl:consts.API_BASE_URL + '/xsdcrm-wechat-api/riders/maintain/signUpload',
      dormitoryId:'',
      uploadHeader:{
        Authorization:"Bearer " + uni.getStorageSync("token")
      }
    };
  },
  // 必须要在onReady生命周期，因为onLoad生命周期组件可能尚未创建完毕
  onReady() {
    this.$refs.uForm.setRules(this.rules);
  },
  async onLoad(query) {
    this.dormitoryId = query.dormitoryId
    let res3 = await this.$api.dormitory.getShowDormitory(this.dormitoryId)
    let data = res3.data
    if (isEmpty(data) || isEmpty(data.ridersDormitory)) {
      this.show = true
      return
    }
    this.form = Object.assign({},data.sysUser,data.ridersDormitory)
    this.form.dormitoryAddress = this.form.residenceAddress
    this.form.dormitoryId = this.dormitoryId
    let cleaningName = uni.getStorageSync("cleaningName")
    if (cleaningName) {
      this.form.cleaningName = cleaningName.nickName
      this.form.cleaningPhone = cleaningName.phonenumber
    }

  },
  methods:{
    repairsProjectFunc(){
      this.showContactRelationSel = true
    },
    uploadRemove(index, lists, name) {
      console.log(webIndex, lists, name)
      delete this.fileList[webIndex]
      this.fileList = this.fileList.filter(v => {
        return v
      })
    },
    uploadRemove2(index, lists, name) {
      delete this.fileList2[webIndex]
      this.fileList2 = this.fileList2.filter(v => {
        return v
      })
    },
    uploadRemove3(index, lists, name) {
      delete this.fileList3[webIndex]
      this.fileList3 = this.fileList3.filter(v => {
        return v
      })
    },
    uploadRemove4(index, lists, name) {
      delete this.fileList4[webIndex]
      this.fileList4 = this.fileList4.filter(v => {
        return v
      })
    },
    uploadRemove5(index, lists, name) {
      delete this.fileList5[webIndex]
      this.fileList5 = this.fileList5.filter(v => {
        return v
      })
    },
    uploadSuccess(reslut){
      let param = {
        cleaningId:'',
        dormitoryPhoto:reslut.fileName,
        type:2
      }
      this.fileList.push(param)
    },
    uploadSuccess2(reslut){
      let param = {
        cleaningId:'',
        dormitoryPhoto:reslut.fileName,
        type:3
      }
      this.fileList2.push(param)
    },
    uploadSuccess3(reslut){
      let param = {
        cleaningId:'',
        dormitoryPhoto:reslut.fileName,
        type:4
      }
      this.fileList3.push(param)
    },
    uploadSuccess4(reslut){
      let param = {
        cleaningId:'',
        dormitoryPhoto:reslut.fileName,
        type:5
      }
      this.fileList4.push(param)
    },
    uploadSuccess5(reslut){
      let param = {
        cleaningId:'',
        dormitoryPhoto:reslut.fileName,
        type:6
      }
      this.fileList5.push(param)
    },
    jointUrl(url) {
      // return (window.location.href.includes('/xsdcrm-wechat-ui/')?consts.API_BASE_URL+'/xsdcrm-static/upload/': '/profile/')
      return (window.location.href.includes('/xsdcrm-wechat-ui/')?consts.API_BASE_URL+'/xsdcrm-static/upload/': '/profile/') + url
    },
    selectedContactRelation(e){
      this.form.repairsProject = e[0].value
      this.form.repairsProject2 = e[0].label
    },
    async submitFunc(type) {
      console.log(type)

      if (type == 'success') {
        setTimeout(()=>{
          uni.reLaunch({
            url: `/pages/serve/cleaning/loginWebIndex?role=2`
          })
        },600)
        return
      }

      let flag = true
      let flag2 = true
      let flag3 = true
      let flag4 = true
      let flag5 = true
      let fileList = [...this.fileList,...this.fileList2,...this.fileList3,...this.fileList4,...this.fileList5]

      fileList.forEach(v=>{
        if (v.type == 2){
          flag = false
        }
        if (v.type == 3){
          flag2 = false
        }
        if (v.type == 4){
          flag3 = false
        }
        if (v.type == 5){
          flag4 = false
        }
        if (v.type == 6){
          flag5 = false
        }
      })
      if (flag) return uni.showToast({title:"请上传宿舍客厅照片",icon: "error",});
      if (flag2) return uni.showToast({title:"请上传宿舍房间照片",icon: "error",});
      if (flag3) return uni.showToast({title:"请上传宿舍厕所照片",icon: "error",});
      if (flag4) return uni.showToast({title:"请上传宿舍厨房照片",icon: "error",});
      if (flag5) return uni.showToast({title:"请上传宿舍阳台照片",icon: "error",});
      this.$refs.uForm.validate(async (valid) => {
        if (valid) {
          uni.showLoading({
            title: '申请中'
          });
          let openId = uni.getStorageSync('openId')
          this.form.openId = openId
          const {code,msg,data} = await this.$api.dormitory.addCleaning(this.form).catch((e)=>{
          })
          let num = 0
          if (code == 200) {
            fileList.forEach((v,i)=>{
              v.cleaningId = data
              v.openId = openId
              this.$api.dormitory.addMatia(v).catch((e)=>{})
              num++
            })
            console.log('num,this.fileList.length',num,this.fileList.length)
            if (num >= this.fileList.length) {
              uni.showToast({
                title: '提交成功',
                icon: "none",
              });
              setTimeout(()=>{
                uni.reLaunch({
                  url: `/pages/serve/cleaning/loginWebIndex?role=2`
                })
              },600)
              this.isSuccess = true
              uni.hideLoading();
            }
          }
        } else {
          console.log('验证失败');
        }
      });
    },
    dateInterval(Time){
      // 获取今天的日期
      const today = new Date();
      const specifiedDateStr = Time;
      const specifiedDate = new Date(specifiedDateStr);
      const timeDiff = today.getTime() - specifiedDate.getTime();
      const daysDiff = Math.ceil(timeDiff / (1000 * 3600 * 24));
      return daysDiff
    },
    nowTime(){
      const now = new Date();
      // 获取年、月、日
      const year = now.getFullYear();
      let month = (now.getMonth() + 1).toString().padStart(2, '0'); // 月份是从 0 开始计数的，使用padStart方法补零
      let day = now.getDate().toString().padStart(2, '0'); // 获取日期，使用padStart方法补零
      return year+'-'+month+'-'+day
    },
    changeCalendar(e) {
      const nowTime = this.nowTime()
      if (e.result != nowTime) {
        this.form.checkOutTime = e.result
      } else {
        this.form.checkOutTime =  '';
        uni.showToast({
          title: "离宿日期不可选择当天",
          icon: "none",
        });
      }
    },
    checkOutTimeFunc() {
      console.log(11)
      this.calendarShow = true
    },
    async confirmFunc() {
      console.log(this.$api)
      let { code, msg ,data } = await this.$api.dormitory.getRidInfoByIdCard(this.idCardForm.idCardNo).catch(()=>{});
      if (data){
        function judgeGender(idNumber) {
          // 获取身份证号的倒数第二位数字
          const genderDigit = parseInt(idNumber.charAt(idNumber.length - 2));
          // 判断性别
          if (genderDigit % 2 === 0) {
            return '女';
          } else {
            return '男';
          }
        }
        this.form.sex = judgeGender(data.idCardNo)
        this.isCRM = true
        let NewForm = Object.assign({},data,JSON.parse(JSON.stringify(this.form)));
        this.form = JSON.parse(JSON.stringify(NewForm))
        this.$forceUpdate();
      }
      this.idCardPopup = false
    },
    cancelFunc() {

    },
    radioGroupChange(){

    },
    // 删除身份证人像面
    onIdCardBadgeImgDelete() {
      this.form.idCardBadgeImages = null
      this.showIdCardBadgeImages = false
    },
    // 删除身份证国徽面
    onIdCardPortraitImgDelete() {
      this.form.idCardPortraitImages = null
      this.showIdCardPortraitImgPreview = false
    },
    //删除人脸照片
    onHandIdCardImgDelete(item,index) {
      delete this.fileList[webIndex]
      this.fileList = this.fileList.filter(v =>{ return v })
      this.showImages = false
    },
    // 上传图片
    async uploadPic(file, name,type) {
      try {
        const res = await uploadImg(file,'/xsdcrm-wechat-api/wxseparateAgreement/signUpload',false);
        let param = {
          maintainId:'',
          damageItem:res.fileName,
          status:type
        }
        this.fileList.push(param)
      } catch (e) {
      }
    },
    // 照片选择后回调
    onHandIdCardChooseCallback(lists) {
      // 压缩图片
      compressImg({
        file: lists[0].file, success: (result) => {
          this.uploadPic(result,'repairsImage',1)
          this.showImages = true
        }
      })
    },
  }
};
</script>
<style scoped>
*{
  box-sizing: border-box;
}
.view-class{
  width: 100%;
  height: 100vh;
}
.view-box{
  padding:0 30rpx;
  padding-bottom: 120rpx;
}
.container {
  height: 200vh;
  margin-top: 150rpx;
}

.sticky {
  width: 750rpx;
  height: 120rpx;
  background-color: #2979ff;
  color: #fff;
  padding: 24rpx;
}
.u-form-item{
  padding-right: 30rpx;
}

/deep/.u-star-wrap{
  line-height: 1;
}
.newAddImg{
  width:166rpx;
  height: 166rpx;
  overflow: hidden;
  margin: 5px;
  background: #f4f5f6;
  position: relative;
  border-radius: 5px;
  display: flex;
  -webkit-box-align: center;
  -webkit-align-items: center;
  align-items: center;
  -webkit-box-pack: center;
  -webkit-justify-content: center;
  justify-content: center;
  flex-direction: column;
  align-items: center;
}

/deep/.u-input__textarea{
  min-height: auto!important;
}
</style>
